import { readonly, reactive, inject } from "vue";
import * as userServ from "../api/user";
const key = Symbol(); // Provide的key

// 在传入的vue应用实例中提供数据
export function provideStore(app) {
    // 创建默认的响应式数据
    const state = reactive({ user: null, loading: false });
    // 登录
    async function login(loginId, loginPwd) {
        state.loading = true;
        const user = await userServ.login(loginId, loginPwd);
        state.user = user;
        state.loading = false;
    }
    // 退出
    async function loginOut() {
        state.loading = true;
        await userServ.loginOut();
        state.loading = false;
        state.user = null;
    }
    // 恢复登录状态
    async function whoAmI() {
        state.loading = true;
        const user = await userServ.whoAmI();
        state.loading = false;
        state.user = user;
    }
    // 提供全局数据
    app.provide(key, {
        state: readonly(state), // 对外只读
        login,
        loginOut,
        whoAmI,
    });
}

export function useStore(defaultValue = null) {
    return inject(key, defaultValue);
}
